<?php
namespace Commons\MobileControl;

use Commons\App;

class  Base
{
    private $api = null;
    private $iv = '0102030405060708';

    /**
     * @param array  $params
     * @param string $method
     *
     * @return string
     * @throws \Exception
     */
    public function prepare(array $params, $method = 'api.car.list')
    {
        try {
            if (is_array($params) && count($params) > 0) {
                $appSecret = App::globalConfig()->kulala->appSecret;
                $api       = App::globalConfig()->kulala->api;
                $api       = $api . (strpos($api, '?') ? '&' : '?');
                $appKey    = App::globalConfig()->kulala->appKey;
                $json      = json_encode(array_merge($params, ['appKey' => $appKey]));
                $verifyStr = urlencode($this->encrypt($json, $appSecret));
                $params    = 'params=' . $verifyStr . '&method=' . trim($method);
                $this->api = $api . $params . '&appKey=' . $appKey;
                return $this->api;
            }
        } catch (\Exception $ex) {
            throw new \Exception('配置参数丢失');
        }
        return $this->api;
    }

    /**
     * @param $input
     * @param $secret
     *
     * @return string
     */
    public function encrypt($input, $secret)
    {
        return base64_encode(openssl_encrypt($input, 'AES-128-CBC', $secret, OPENSSL_RAW_DATA, $this->iv));
    }

    /**
     * @param $input
     * @param $secret
     *
     * @return string
     */
    public function decrypt($input, $secret)
    {
        return openssl_decrypt(base64_decode($input), 'AES-128-CBC', $secret, OPENSSL_RAW_DATA, $this->iv);
    }
}
